﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using Cleverscape.UTorrentClient.WebClient.ServiceDefinition;
using System.ComponentModel;
using System.Windows.Threading;
using GalaSoft.MvvmLight.Threading;

namespace Cleverscape.UTorrentClient.WebClient
{
    /// <summary>
    /// Represents a collection of Filters
    /// </summary>
    public class FilterCollection : IList<Filter>, INotifyCollectionChanged, INotifyPropertyChanged
    {

        private List<Filter> _FilterCollectionInternal;

        internal UTorrentWebClient ParentClient { get; private set; }

        internal FilterCollection(UTorrentWebClient ParentClient)
        {
            this.ParentClient = ParentClient;
            _FilterCollectionInternal = new List<Filter>();
        }

        public FilterCollection()
        {
            _FilterCollectionInternal = new List<Filter>();
            for (int i = 0; i < 5; i++)
            {
                Filter f = new Filter();
                _FilterCollectionInternal.Add(f);
            }
        }

        #region Internal Methods

        internal void Parse(FiltersList FiltersToParse, bool IsFresh)
        {
            List<int> ListOfIdents = new List<int>();
            foreach (string[] FilterArray in FiltersToParse)
            {
                if (FilterArray.Length == 0)
                {
                    throw new FormatException("The array of Filter data was not in the expected format.");
                }
                ListOfIdents.Add(Convert.ToInt32(FilterArray[0]));
                Filter NewFilter = GetByIdent(Convert.ToInt32(FilterArray[0]));
                if (NewFilter == null)
                {
                    NewFilter = new Filter(FilterArray, this);
                    _FilterCollectionInternal.Add(NewFilter);
                    if (!IsFresh)
                    {
                        //ParentClient.CallEvent(UTorrentWebClient.EventType.Added, NewFilter);
                    }
                    CallCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, NewFilter, this.Count-1));
                }
                else
                {
                    NewFilter.UpdateValuesFromStringArray(FilterArray);

                }
            }
            IEnumerable<Filter> RemovedFilters = RemoveWhereIdentIsNotInList(ListOfIdents);
            foreach (Filter RemovedFilter in RemovedFilters)
            {
                CallCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, RemovedFilter, this.IndexOf(RemovedFilter)));
            }
        }

        internal void Parse(RemovedFiltersList RemovedFiltersToParse, ChangedFiltersList ChangedFiltersToParse)
        {
            if (RemovedFiltersToParse == null || ChangedFiltersToParse == null)
            {
                return;
            }
            else
            {
                List<Filter> RemovedFilters = new List<Filter>();
                foreach (string Filter in RemovedFiltersToParse)
                {
                    //if (FilterArray.Length == 0)
                    //{
                    //    throw new FormatException("The array of Filter data was not in the expected format.");
                    //}
                    RemovedFilters.Clear();
                    RemovedFilters.AddRange(RemoveByIdent(Convert.ToInt32(Filter)));
                    //foreach (Filter RemovedFilter in RemovedFilters)
                    //{
                        
                    //}
                }
                foreach (object[] FilterArray in ChangedFiltersToParse)
                {
                    if (FilterArray.Length == 0)
                    {
                        throw new FormatException("The array of Filter data was not in the expected format.");
                    }
                    Filter NewFilter = GetByIdent(Convert.ToInt32(FilterArray[0]));
                    if (NewFilter == null)
                    {
                        NewFilter = new Filter(FilterArray, this);
                        _FilterCollectionInternal.Add(NewFilter);
                        //ParentClient.CallEvent(UTorrentWebClient.EventType.Added, NewFilter);
                        CallCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, NewFilter, this.Count-1));
                    }
                    else
                    {
                        NewFilter.UpdateValuesFromStringArray(FilterArray);
                    }
                }
            }
        }

        private IEnumerable<Filter> RemoveByIdent(int Ident)
        {
            List<Filter> FiltersToRemove = new List<Filter>();
            foreach (Filter CurrentFilter in _FilterCollectionInternal)
            {
                if (CurrentFilter.Ident == Ident)
                {
                    FiltersToRemove.Add(CurrentFilter);
                }
            }
            foreach (Filter FilterToRemove in FiltersToRemove)
            {
                int idx = _FilterCollectionInternal.IndexOf(FilterToRemove);
                _FilterCollectionInternal.Remove(FilterToRemove);
                CallCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, FilterToRemove, idx));

            }
            return FiltersToRemove;
        }

        private IEnumerable<Filter> RemoveWhereIdentIsNotInList(IEnumerable<int> ListOfIdents)
        {
            List<Filter> FiltersToRemove = new List<Filter>();
            foreach (Filter CurrentFilter in _FilterCollectionInternal)
            {
                if (!ListOfIdents.Contains(CurrentFilter.Ident))
                {
                    FiltersToRemove.Add(CurrentFilter);
                }
            }
            foreach (Filter FilterToRemove in FiltersToRemove)
            {
                _FilterCollectionInternal.Remove(FilterToRemove);
            }
            return FiltersToRemove;
        }


        private void CallCollectionChanged(NotifyCollectionChangedEventArgs EventArgs)
        {
            DispatcherHelper.UIDispatcher.BeginInvoke(() =>
            {
                if (CollectionChanged != null)
                {
                    if (ParentClient.Dispatcher == null || ParentClient.Dispatcher.CheckAccess())
                    {
                        CollectionChanged(this, EventArgs);
                    }
                    else
                    {
                        ParentClient.Dispatcher.BeginInvoke(new CallCollectionChangedAsyncCallback(CallCollectionChangedAsync), new object[] { EventArgs });
                    }
                }
            });
        }

        private void CallCollectionChangedAsync(NotifyCollectionChangedEventArgs EventArgs)
        {
            CollectionChanged(this, EventArgs);
        }

        private delegate void CallCollectionChangedAsyncCallback(NotifyCollectionChangedEventArgs EventArgs);

        internal void AddFilter(Filter FilterToAdd)
        {
            _FilterCollectionInternal.Add(FilterToAdd);
            this.ParentClient.FilterUpdateAdd(FilterToAdd);
        }

        #endregion

        #region Private Methods

        

        

        #endregion

        #region Public Methods

        public bool Contains(int Ident)
        {
            foreach (Filter CurrentFilter in _FilterCollectionInternal)
            {
                if (CurrentFilter.Ident == Ident)
                {
                    return true;
                }
            }
            return false;
        }

        public Filter GetByIdent(int Ident)
        {
            foreach (Filter CurrentFilter in _FilterCollectionInternal)
            {
                if (CurrentFilter.Ident == Ident)
                {
                    return CurrentFilter;
                }
            }
            return null;
        }

        

        public void Insert(int index, Filter item)
        {
        }

        public void Clear()
        {
        }

        public void Add(Filter item)
        {
            AddFilter(item);
        }

        public int IndexOf(Filter item)
        {
            return _FilterCollectionInternal.IndexOf(item);
        }

        public void RemoveAt(int index)
        {
            throw new NotImplementedException();
        }

        public Filter this[int index]
        {
            get
            {
                return _FilterCollectionInternal[index];
            }
            set
            {
            }
        }

        public bool Contains(Filter item)
        {
            return (GetByIdent(item.Ident) != null);
        }

        public void CopyTo(Filter[] array, int arrayIndex)
        {
            _FilterCollectionInternal.CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return _FilterCollectionInternal.Count; }
        }

        public bool IsReadOnly
        {
            get { return true; }
        }

        public bool Remove(Filter item)
        {
            if (GetByIdent(item.Ident) != null)
            {
                item.Remove();
                _FilterCollectionInternal.Remove(item);
                return true;
            }
            return false;
        }

        public IEnumerator<Filter> GetEnumerator()
        {
            return _FilterCollectionInternal.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _FilterCollectionInternal.GetEnumerator();
        }

        #endregion

        #region Public Events (Interface Implementation)

        public event NotifyCollectionChangedEventHandler CollectionChanged;

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(string PropertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
            }
        }

        #endregion

    }
}
